package leetcode;

public class LeetCode63 {

    public int uniquePathsWithObstacles1(int[][] obstacleGrid) {
        int m = obstacleGrid.length, n = obstacleGrid[0].length;
        if (m == 1) {
            boolean haveObstacle = false;
            for (int i = 0; i < n; i++) {
                if (obstacleGrid[0][i] == 1) {
                    haveObstacle = true;
                    break;
                }
            }
            return haveObstacle ? 0 : 1;
        }
        if (n == 1) {
            boolean haveObstacle = false;
            for (int i = 0; i < m; i++) {
                if (obstacleGrid[i][0] == 1) {
                    haveObstacle = true;
                    break;
                }
            }
            return haveObstacle ? 0 : 1;
        }
        int[][] dp = new int[m][n];
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                if (obstacleGrid[i][j] == 1)
                    dp[i][j] = 0;
                else if (i == m - 1 || j == n - 1)
                    dp[i][j] = 1;
                else
                    dp[i][j] = dp[i + 1][j] + dp[i][j + 1];
            }
        }
        return dp[0][0];
    }
//------------------------------------------------------------------

    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int n = obstacleGrid.length, m = obstacleGrid[0].length;
        int[] f = new int[m];

        f[0] = obstacleGrid[0][0] == 0 ? 1 : 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (obstacleGrid[i][j] == 1) {
                    f[j] = 0;
                    continue;
                }
                if (j - 1 >= 0 && obstacleGrid[i][j - 1] == 0) {
                    f[j] += f[j - 1];
                }
            }
        }

        return f[m - 1];
    }
}
